package org.example.rabbitmq.client.rpc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RPCClient {
    RPCClientInner client;

    public RPCClient() throws IOException, TimeoutException {
        client = new RPCClientInner();
    }

    @Override
    protected void finalize() throws Throwable {
        close();
    }

    public void close() throws IOException {
        if (client != null) {
            client.close();
            client = null;
        }
    }

    public String request(String body) throws IOException, InterruptedException {
        System.out.println("[x] Requesting from client: " + body);
        String response = client.request(body);
        return response;
    }

    public class RPCClientInner {
        private Connection connection;
        private Channel channel;
        private String replyQueueName;

        public RPCClientInner() throws IOException, TimeoutException {
            connection = newConnection();
            channel = connection.createChannel();
            replyQueueName = channel.queueDeclare().getQueue();
        }

        private Connection newConnection() throws IOException, TimeoutException {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            factory.setUsername("guest");
            factory.setPassword("guest@local");
            return factory.newConnection();
        }

        public String request(String message) throws IOException, InterruptedException {
            String corrId = UUID.randomUUID().toString();

            AMQP.BasicProperties props = new AMQP.BasicProperties
                    .Builder()
                    .correlationId(corrId)
                    .replyTo(replyQueueName)
                    .build();

            channel.basicPublish("", Names.RPC_QUEUE_NAME, props, message.getBytes("UTF-8"));

            final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
            channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    if (properties.getCorrelationId().equals(corrId)) {
                        response.offer(new String(body, "UTF-8"));
                    }
                }
            });

            return response.take();
        }

        public void close() throws IOException {
            connection.close();
        }
    }
}
